#!/usr/bin/env python3
"""
BoLe 智能HR系统启动器
基于真实数据的对话式招聘管理系统

🎯 核心功能:
• 对话即筛选：通过自然语言筛选候选人
• 对话即洞察：深度分析和评估候选人
• 对话即管理：管理候选人状态、备注、标签

🚀 技术栈:
• LangChain + RAG 检索增强生成
• 真实简历和岗位数据 (66,000+ 简历)
• FastAPI + 现代化前端界面
"""

import os
import sys
import asyncio
import logging
from pathlib import Path
from typing import Dict, Any, Optional
from datetime import datetime

# 添加项目路径
current_dir = Path(__file__).parent
sys.path.append(str(current_dir))

# FastAPI imports
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

# 本地模块
from data_manager import data_manager
from multi_agent_system import multi_agent_hr_system

# 日志配置
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

# FastAPI 应用
app = FastAPI(
    title="BoLe 智能HR系统",
    description="基于对话的智能招聘管理系统",
    version="1.0.0"
)

# CORS 配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True, 
    allow_methods=["*"],
    allow_headers=["*"],
)

# 静态文件服务配置
frontend_dir = os.path.join(os.path.dirname(__file__), "frontend")
if os.path.exists(frontend_dir):
    app.mount("/static", StaticFiles(directory=frontend_dir), name="static")
    logger.info(f"✅ 前端静态文件已挂载: {frontend_dir}")
else:
    logger.warning(f"⚠️ 前端目录不存在: {frontend_dir}")

@app.get("/", response_class=HTMLResponse)
async def serve_index():
    """服务首页"""
    index_path = os.path.join(frontend_dir, "index.html")
    if os.path.exists(index_path):
        return FileResponse(index_path)
    else:
        return HTMLResponse("<h1>前端文件未找到</h1><p>请确保 frontend/index.html 文件存在</p>", status_code=404)

# 全局状态
app_state = {
    "initialized": False,
    "start_time": datetime.now(),
    "request_count": 0,
    "error_count": 0
}

@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("🚀 启动BoLe智能HR系统...")
    
    try:
        # 初始化多智能体HR系统
        success = multi_agent_hr_system.initialize()
        
        if success:
            app_state["initialized"] = True
            candidate_count = len(data_manager.resumes)
            job_count = len(data_manager.jobs)
            
            logger.info("✅ 多智能体HR系统初始化成功!")
            logger.info(f"📊 数据统计: {candidate_count} 个候选人, {job_count} 个岗位")
            logger.info("🤖 多智能体协作系统已就绪 - Interaction → Orchestrator → Specialists → Tools → Completion")
        else:
            logger.error("❌ 多智能体HR系统初始化失败")
            app_state["initialized"] = False
            
    except Exception as e:
        logger.error(f"💥 系统启动异常: {e}")
        app_state["initialized"] = False



@app.get("/api/status")
async def get_status():
    """获取系统状态"""
    try:
        uptime = (datetime.now() - app_state["start_time"]).total_seconds()
        
        return JSONResponse(content={
            "success": True,
            "system_status": "healthy" if app_state["initialized"] else "error",
            "initialized": app_state["initialized"],
            "uptime_seconds": uptime,
            "candidate_count": len(data_manager.resumes) if app_state["initialized"] else 0,
            "job_count": len(data_manager.jobs) if app_state["initialized"] else 0,
            "request_count": app_state["request_count"],
            "error_count": app_state["error_count"],
            "timestamp": datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"获取状态失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.post("/api/chat")
async def chat_endpoint(request_data: Dict[str, Any]):
    """聊天接口"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成，请稍后重试")
        
        message = request_data.get("message", "").strip()
        if not message:
            raise HTTPException(status_code=400, detail="消息不能为空")
        
        if len(message) > 1000:
            raise HTTPException(status_code=400, detail="消息长度不能超过1000字符")
        
        # 增加请求计数
        app_state["request_count"] += 1
        
        logger.info(f"💬 收到用户消息: {message[:50]}...")
        
        # 处理消息（使用多智能体HR系统）
        response_data = await multi_agent_hr_system.process_request(message)
        
        logger.info(f"🤖 多智能体处理状态: {response_data.get('status', 'unknown')}")
        logger.info(f"🎯 智能体工作流: {response_data.get('agent_workflow', '未知')}")
        
        # 返回多智能体系统响应
        if response_data.get("success"):
            return JSONResponse(content={
                **response_data,
                "candidate_count": len(data_manager.resumes),
                "timestamp": datetime.now().isoformat()
            })
        else:
            return JSONResponse(content={
                "success": False,
                "error": response_data.get("error", "处理失败"),
                "action_type": "error",
                "timestamp": datetime.now().isoformat()
            }, status_code=500)
        
    except HTTPException as e:
        raise e
    except Exception as e:
        app_state["error_count"] += 1
        logger.error(f"💥 聊天处理失败: {e}")
        
        return JSONResponse(content={
            "success": False,
            "error": f"处理消息时发生错误: {str(e)}",
            "action_type": "error",
            "timestamp": datetime.now().isoformat()
        }, status_code=500)

@app.get("/api/candidates")
async def get_candidates(limit: int = 20, offset: int = 0):
    """获取候选人列表"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        candidates = data_manager.resumes[offset:offset + limit]
        
        candidate_list = []
        for resume in candidates:
            candidate_list.append({
                "id": resume.id,
                "name": resume.name or f"候选人_{resume.id}",
                "category": resume.category,
                "skills": resume.skills,
                "experience_years": resume.experience_years,
                "status": "active",  # 简化状态管理
                "tags": [],
                "notes_count": 0
            })
        
        return JSONResponse(content={
            "success": True,
            "data": candidate_list,
            "total": len(data_manager.resumes),
            "offset": offset,
            "limit": limit
        })
        
    except Exception as e:
        logger.error(f"获取候选人失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.get("/api/jobs")
async def get_jobs():
    """获取岗位列表"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        jobs_list = []
        for i, job in enumerate(data_manager.jobs):
            jobs_list.append({
                "id": job.id,
                "title": job.title,
                "full_title": job.short_title,  # 前端期望的字段名
                "company": job.company_name,
                "location": job.location,
                "salary": job.salary_year_avg,
                "required_skills": job.required_skills,
                "preferred_skills": job.preferred_skills,
                "min_experience": job.min_experience_years,
                "description": job.description[:200] + "..." if len(job.description) > 200 else job.description,
                "urgent": i == 0,  # 第一个岗位设为紧急
                "applicants": 12 + (i * 7)  # 模拟申请人数
            })
        
        return JSONResponse(content={
            "success": True,
            "data": jobs_list,
            "total": len(data_manager.jobs)
        })
        
    except Exception as e:
        logger.error(f"获取岗位失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.get("/api/jobs/{job_id}/candidates")
async def get_job_candidates(job_id: str):
    """获取指定岗位的候选人列表"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        # 验证岗位存在
        job = data_manager.get_job_by_id(job_id)
        if not job:
            raise HTTPException(status_code=404, detail=f"岗位 {job_id} 不存在")
        
        # 获取候选人列表 (简化：返回所有候选人)
        candidates = data_manager.resumes[:20]  # 限制数量
        
        candidate_list = []
        for i, resume in enumerate(candidates):
            # 确保有真实的简历内容
            full_content = resume.content if resume.content else f"暂无简历详细内容 - {resume.name or f'候选人_{resume.id}'}"
            
            # 从简历内容中提取更多信息
            enriched_info = extract_resume_info(full_content, resume)
            
            candidate_list.append({
                "id": resume.id,
                "name": resume.name or f"候选人_{resume.id[:8]}",
                "category": resume.category or "未分类",
                "skills": resume.skills or ["暂无技能信息"],
                "experience_years": resume.experience_years or enriched_info.get("experience_years", 0),
                "status": "active",
                "tags": [],
                "notes": "",  # 添加notes字段
                "notes_count": 0,
                "score": round(7.0 + (hash(resume.id) % 30) / 10.0, 1),  # 模拟评分 7.0-9.9
                "match_percentage": 75 + (i % 25),  # 模拟匹配度 75-99%
                "resume_full_text": full_content,  # 添加完整简历内容
                "resume_preview": full_content[:300] + "..." if len(full_content) > 300 else full_content,
                "education": enriched_info.get("education", "未知学历"),
                "location": enriched_info.get("location", "北京"),
                "salary_expectation": enriched_info.get("salary_expectation", f"{15 + i * 2}-{20 + i * 3}k"),
                "contact_info": enriched_info.get("contact_info", {
                    "email": f"candidate_{resume.id[:8]}@example.com",
                    "phone": f"138****{1000 + i:04d}"
                }),
                # 新增丰富信息
                "projects": enriched_info.get("projects", []),
                "work_history": enriched_info.get("work_history", []),
                "certifications": enriched_info.get("certifications", []),
                "languages": enriched_info.get("languages", []),
                "strengths": enriched_info.get("strengths", []),
                "achievements": enriched_info.get("achievements", [])
            })
        
        return JSONResponse(content={
            "success": True,
            "data": candidate_list,
            "job": {
                "id": job.id,
                "title": job.title,
                "company": job.company_name
            },
            "total": len(candidate_list)
        })
        
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"获取岗位候选人失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.get("/api/candidate/{candidate_id}")
async def get_candidate_detail(candidate_id: str):
    """获取候选人详情"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        resume = data_manager.get_resume_by_id(candidate_id)
        if not resume:
            raise HTTPException(status_code=404, detail="候选人不存在")
        
        # 获取候选人的笔记信息
        notes_info = app_state.get("candidate_notes", {}).get(candidate_id, {})
        
        # 从简历内容中提取丰富信息
        full_content = resume.content if resume.content else f"暂无简历详细内容 - {resume.name or candidate_id}"
        enriched_info = extract_resume_info(full_content, resume)
        
        return JSONResponse(content={
            "success": True,
            "data": {
                "id": resume.id,
                "name": resume.name or f"候选人_{resume.id[:8]}",
                "category": resume.category or "未分类",
                "skills": resume.skills or ["暂无技能信息"],
                "experience_years": resume.experience_years or enriched_info.get("experience_years", 0),
                "content": full_content,
                "resume_full_text": full_content,
                "status": "active",
                "tags": [],
                "notes": notes_info.get("notes", ""),
                "score": round(7.0 + (hash(resume.id) % 30) / 10.0, 1),
                "last_updated": notes_info.get("updated_at"),
                "education": enriched_info.get("education", "未知学历"),
                "location": enriched_info.get("location", "北京"),
                "salary_expectation": enriched_info.get("salary_expectation", "15-25k"),
                "contact_info": enriched_info.get("contact_info", {
                    "email": f"candidate_{resume.id[:8]}@example.com",
                    "phone": f"138****{abs(hash(resume.id)) % 10000:04d}"
                }),
                "pdf_url": f"/api/candidates/{candidate_id}/pdf",
                # 新增丰富信息
                "projects": enriched_info.get("projects", []),
                "work_history": enriched_info.get("work_history", []),
                "certifications": enriched_info.get("certifications", []),
                "languages": enriched_info.get("languages", []),
                "strengths": enriched_info.get("strengths", []),
                "achievements": enriched_info.get("achievements", [])
            }
        })
        
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"获取候选人详情失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.get("/api/jobs/{job_id}")
async def get_job_detail(job_id: str):
    """获取岗位详情"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        job = data_manager.get_job_by_id(job_id)
        if not job:
            raise HTTPException(status_code=404, detail=f"岗位 {job_id} 不存在")
        
        return JSONResponse(content={
            "success": True,
            "data": {
                "id": job.id,
                "title": job.title,
                "full_title": job.short_title,
                "company": job.company_name,
                "location": job.location,
                "salary": job.salary_year_avg,
                "required_skills": job.required_skills,
                "preferred_skills": job.preferred_skills,
                "min_experience": job.min_experience_years,
                "description": job.description,
                "urgent": job_id == "0",  # 第一个岗位为紧急
                "applicants": 12 + int(job_id) * 7,
                "posted_date": "2024-01-15",
                "status": "active"
            }
        })
        
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"获取岗位详情失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.get("/api/candidates/{candidate_id}/pdf")
async def get_candidate_pdf(candidate_id: str):
    """获取候选人PDF简历"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        resume = data_manager.get_resume_by_id(candidate_id)
        if not resume:
            raise HTTPException(status_code=404, detail="候选人不存在")
        
        # 返回PDF内容或重定向到PDF URL
        # 这里模拟返回原始简历内容作为文本
        from fastapi.responses import PlainTextResponse
        
        full_content = f"""
# 候选人简历 - {resume.name or f'候选人_{candidate_id[:8]}'}

## 基本信息
- 姓名: {resume.name or '未提供'}
- 类别: {resume.category or '未分类'}
- 工作经验: {resume.experience_years or 0}年
- 技能: {', '.join(resume.skills) if resume.skills else '暂无'}

## 完整简历内容
{resume.content if resume.content else '暂无详细简历内容'}

---
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
"""
        
        return PlainTextResponse(
            content=full_content,
            headers={
                "Content-Disposition": f"attachment; filename=resume_{candidate_id[:8]}.txt"
            }
        )
        
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"获取候选人PDF失败: {e}")
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

@app.post("/api/candidates/{candidate_id}/notes")
async def update_candidate_notes_api(candidate_id: str, request_data: Dict[str, Any]):
    """更新候选人笔记API"""
    try:
        if not app_state["initialized"]:
            raise HTTPException(status_code=503, detail="系统尚未初始化完成")
        
        logger.info(f"📝 接收到笔记更新请求: {candidate_id}")
        logger.info(f"📋 请求数据: {request_data}")
        
        notes = request_data.get("notes", "")
        
        # 验证候选人存在
        resume = data_manager.get_resume_by_id(candidate_id)
        if not resume:
            raise HTTPException(status_code=404, detail="候选人不存在")
        
        # 初始化笔记存储
        if "candidate_notes" not in app_state:
            app_state["candidate_notes"] = {}
        
        # 更新笔记
        app_state["candidate_notes"][candidate_id] = {
            "notes": notes,
            "updated_at": datetime.now().isoformat(),
            "updated_by": "system"
        }
        
        logger.info(f"✅ 笔记更新成功: {candidate_id} -> '{notes[:50]}...'")
        
        return JSONResponse(content={
            "success": True,
            "message": f"候选人 {candidate_id} 的笔记已更新",
            "data": {
                "candidate_id": candidate_id,
                "notes": notes,
                "updated_at": datetime.now().isoformat()
            }
        })
        
    except HTTPException as e:
        logger.error(f"❌ HTTP错误: {e.detail}")
        raise e
    except Exception as e:
        logger.error(f"❌ 更新候选人笔记失败: {e}")
        import traceback
        logger.error(f"❌ 详细错误: {traceback.format_exc()}")
        return JSONResponse(content={
            "success": False,
            "error": f"更新笔记失败: {str(e)}",
            "message": f"更新候选人笔记时发生错误"
        }, status_code=500)

def extract_resume_info(content: str, resume) -> dict:
    """从简历内容中提取丰富信息"""
    import re
    
    enriched_info = {}
    content_lower = content.lower()
    
    # 提取教育信息
    education_keywords = ['bachelor', 'master', 'phd', 'doctorate', 'university', 'college', '本科', '硕士', '博士', '大学']
    education_found = []
    for keyword in education_keywords:
        if keyword in content_lower:
            education_found.append(keyword.capitalize())
    
    if education_found:
        if any(x in education_found for x in ['Master', '硕士']):
            enriched_info["education"] = "硕士"
        elif any(x in education_found for x in ['Phd', 'Doctorate', '博士']):
            enriched_info["education"] = "博士"
        elif any(x in education_found for x in ['Bachelor', '本科']):
            enriched_info["education"] = "本科"
        else:
            enriched_info["education"] = "本科"
    else:
        enriched_info["education"] = "本科"  # 默认
    
    # 提取位置信息
    cities = ['beijing', 'shanghai', 'shenzhen', 'guangzhou', 'hangzhou', 'nanjing', 'wuhan', 'chengdu', 
              '北京', '上海', '深圳', '广州', '杭州', '南京', '武汉', '成都']
    for city in cities:
        if city in content_lower:
            enriched_info["location"] = city.capitalize() if city.isalpha() else city
            break
    else:
        enriched_info["location"] = "北京"  # 默认
    
    # 提取项目经验
    projects = []
    project_patterns = [
        r'project[:\s]+([^\n]+)',
        r'项目[：:\s]*([^\n]+)',
        r'开发了?\s*([^\n，。]+)',
        r'负责\s*([^\n，。]+)'
    ]
    
    for pattern in project_patterns:
        matches = re.findall(pattern, content, re.IGNORECASE)
        for match in matches[:3]:  # 最多3个项目
            if len(match.strip()) > 10:  # 过滤太短的
                projects.append(match.strip()[:100])  # 限制长度
    
    enriched_info["projects"] = projects[:3]  # 最多3个
    
    # 提取工作经历
    work_history = []
    work_patterns = [
        r'(?:worked at|work at|在.*工作|任职于)\s*([^\n]+)',
        r'(?:company|公司)[:\s]*([^\n]+)',
        r'(?:position|职位)[:\s]*([^\n]+)'
    ]
    
    for pattern in work_patterns:
        matches = re.findall(pattern, content, re.IGNORECASE)
        for match in matches[:2]:  # 最多2个工作经历
            if len(match.strip()) > 5:
                work_history.append(match.strip()[:80])
    
    enriched_info["work_history"] = work_history[:2]
    
    # 提取认证信息
    cert_keywords = ['certified', 'certification', 'certificate', 'aws', 'azure', 'google cloud', 'pmp', '认证', '证书']
    certifications = []
    for keyword in cert_keywords:
        if keyword in content_lower:
            certifications.append(keyword.upper())
    
    enriched_info["certifications"] = list(set(certifications))[:3]  # 去重，最多3个
    
    # 提取语言能力
    language_keywords = ['english', 'chinese', 'japanese', 'korean', 'french', 'german', '英语', '中文', '日语', '韩语']
    languages = []
    for lang in language_keywords:
        if lang in content_lower:
            languages.append(lang.capitalize())
    
    enriched_info["languages"] = list(set(languages))[:3]  # 去重，最多3个
    
    # 提取核心优势
    strength_patterns = [
        r'(?:strong in|擅长|优势)[:\s]*([^\n]+)',
        r'(?:expert in|专家)[:\s]*([^\n]+)',
        r'(?:proficient in|精通)[:\s]*([^\n]+)'
    ]
    
    strengths = []
    for pattern in strength_patterns:
        matches = re.findall(pattern, content, re.IGNORECASE)
        for match in matches[:3]:
            if len(match.strip()) > 5:
                strengths.append(match.strip()[:60])
    
    enriched_info["strengths"] = strengths[:3]
    
    # 提取成就
    achievement_patterns = [
        r'(?:achieved|accomplishment|成就|获得)[:\s]*([^\n]+)',
        r'(?:award|奖项)[:\s]*([^\n]+)',
        r'(?:recognition|表彰)[:\s]*([^\n]+)'
    ]
    
    achievements = []
    for pattern in achievement_patterns:
        matches = re.findall(pattern, content, re.IGNORECASE)
        for match in matches[:2]:
            if len(match.strip()) > 8:
                achievements.append(match.strip()[:80])
    
    enriched_info["achievements"] = achievements[:2]
    
    # 提取经验年限
    exp_patterns = [
        r'(\d+)\s*(?:years?|年)\s*(?:experience|经验)',
        r'(?:experience|经验)[:\s]*(\d+)\s*(?:years?|年)'
    ]
    
    for pattern in exp_patterns:
        match = re.search(pattern, content, re.IGNORECASE)
        if match:
            enriched_info["experience_years"] = int(match.group(1))
            break
    
    # 提取薪资期望
    salary_patterns = [
        r'(?:salary|薪资|薪水)[:\s]*(\d+[k万]?)',
        r'(\d+[k万]?)(?:/month|/年|月薪|年薪)'
    ]
    
    for pattern in salary_patterns:
        match = re.search(pattern, content, re.IGNORECASE)
        if match:
            enriched_info["salary_expectation"] = match.group(1)
            break
    
    # 提取联系信息
    email_match = re.search(r'[\w\.-]+@[\w\.-]+\.\w+', content)
    phone_match = re.search(r'1[3-9]\d{9}', content)
    
    contact_info = {}
    if email_match:
        contact_info["email"] = email_match.group(0)
    if phone_match:
        contact_info["phone"] = phone_match.group(0)
    
    enriched_info["contact_info"] = contact_info
    
    return enriched_info

def print_banner():
    """打印启动横幅"""
    banner = """
╔══════════════════════════════════════════════════════════════════╗
║                    🤖 BoLe 智能HR系统 🤖                          ║
║                  对话式招聘管理 • 革新HR体验                      ║
╠══════════════════════════════════════════════════════════════════╣
║                                                                  ║
║  🎯 核心功能                                                     ║
║    • 对话即筛选: "筛选出所有在北京、有5年以上Java经验的候选人"    ║
║    • 对话即洞察: "总结张三简历里关于项目管理能力的亮点"          ║
║    • 对话即管理: "更新李四的状态为已安排终面"                    ║
║                                                                  ║
║  🚀 技术特色                                                     ║
║    • 基于真实数据 (1,000+ 简历)                                  ║
║    • LangGraph循环推理 + Agent思考⟷工具执行                     ║
║    • 自然语言理解                                               ║
║    • 批量操作支持                                               ║
║                                                                  ║
╚══════════════════════════════════════════════════════════════════╝
"""
    print(banner)

def start_server(host: str = "0.0.0.0", port: int = 8085, debug: bool = False):
    """启动服务器"""
    print_banner()
    
    logger.info(f"🌐 启动服务器配置:")
    logger.info(f"   📍 主机: {host}")
    logger.info(f"   🔌 端口: {port}")
    logger.info(f"   🔗 访问地址: http://{host}:{port}")
    logger.info(f"   🐛 调试模式: {'开启' if debug else '关闭'}")
    
    logger.info("\n💡 使用指南:")
    logger.info("   1. 在浏览器中打开访问地址")
    logger.info("   2. 直接在聊天框中输入需求")
    logger.info("   3. 例如：'筛选出所有Python工程师'")
    logger.info("   4. 支持筛选、分析、对比、管理等功能")
    
    logger.info("\n⚡ 启动中，请稍候...")
    logger.info("=" * 70)
    
    try:
        uvicorn.run(
            app,
            host=host,
            port=port,
            log_level="info" if not debug else "debug",
            access_log=debug
        )
    except KeyboardInterrupt:
        logger.info("\n👋 用户中断，系统关闭")
    except Exception as e:
        logger.error(f"💥 服务器启动失败: {e}")
        raise

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="BoLe智能HR系统启动器")
    parser.add_argument("--host", default="0.0.0.0", help="服务器主机地址")
    parser.add_argument("--port", type=int, default=8085, help="服务器端口")
    parser.add_argument("--debug", action="store_true", help="开启调试模式")
    
    args = parser.parse_args()
    
    start_server(host=args.host, port=args.port, debug=args.debug)
